<?php

namespace App\Observers;

use App\Handlers\SlugTranslateHandler;
use App\Jobs\TranslateSlug;
use App\Models\Tag;
use App\Models\Topic;
use Dcat\Admin\Widgets\Markdown;
use HavenShen\EnjellyDown\Facades\EnjellyDown;
use Illuminate\Support\Facades\DB;
use League\CommonMark\Input\MarkdownInput;
use League\CommonMark\Parser\MarkdownParser;

// creating, created, updating, updated, saving,
// saved,  deleting, deleted, restoring, restored

class TopicObserver
{
    public function saving(Topic $topic)
    {
        // XSS 过滤
        // 启用 XSS 过滤破坏了 markdown 语法结构
        // $topic->body = clean($topic->body, 'custom_definition');

        // 生成话题摘录
        $body = EnjellyDown::markdown($topic->body);

        $topic->excerpt = make_excerpt($body);

        // 设置发布时间
        $topic->publish_at = $topic->publish ? now() : null;
    }

    public function saved(Topic $topic)
    {
        // 如 slug 字段无内容，即使用翻译器对 title 进行翻译
        if (!$topic->slug) {
            // $topic->slug = app(SlugTranslateHandler::class)->translate($topic->title);
            // 推送任务到队列
            dispatch(new TranslateSlug($topic));
        }

        // 更新分类数量
        $topic->category->updateTopicCount();

        // 更新标签数量
        // 一般是保存后 设置多对多关联，这里定义无效
        /*$topic->tags->map(function (Tag $tag) {
            return $tag->updateTopicCount();
        });*/
    }

    public function deleted(Topic $topic)
    {
        // DB::table('replies')->where('topic_id', $topic->id)->delete();
        $topic->replies()->delete();
        // 更新分类
        $topic->category->updateTopicCount();
        // 更新缓存
        $topic->cacheHotTopics();

        // 更新标签数量
        $topic->tags->map(function (Tag $tag) {
            return $tag->updateTopicCount();
        });
    }
}
